package com.aletto.general_store.ui.fragments;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aletto.general_store.R;
import com.aletto.general_store.configs.IBridgeData;
import com.aletto.general_store.configs.SubscribeEventBus;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.model.Goods;
import com.aletto.general_store.data.model.PageResponse;
import com.aletto.general_store.presenters.core.SimplePageTemplate;
import com.aletto.general_store.presenters.core.SimpleParamsTemplate;
import com.aletto.general_store.ui.GoodsGridItemDecoration;
import com.aletto.general_store.ui.activities.GoodsDetailsActivity;
import com.aletto.general_store.ui.adapters.BrowserHistoryAdapter;
import com.aletto.general_store.utils.XHelper;
import com.aletto.general_store.utils.event.FavoritesEvent;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.sisyphus.spinach.core.INetPageTask;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.core.model.IPageResponse;
import com.sisyphus.spinach.core.model.IResponse;
import com.sisyphus.spinach.network.presenters.NetPageTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.core.Observable;
import me.jessyan.autosize.utils.AutoSizeUtils;


/**
 * 收藏商品
 */
public class FavoritesGoodsFragment extends Fragment implements SubscribeEventBus, IBridgeData {

    private RecyclerView recyclerView;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(com.sisyphus.spinach.R.layout.sisyphus_template_refresh_recycler_view, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        recyclerView = view.findViewById(com.sisyphus.spinach.R.id.recycler_view);
        SmartRefreshLayout refreshLayout = view.findViewById(com.sisyphus.spinach.R.id.refresh_layout);

        providerTemplate(recyclerView, refreshLayout).execute(getLifecycle());
    }

    private SimplePageTemplate<Goods> providerTemplate(RecyclerView recyclerView, SmartRefreshLayout refreshLayout) {
        return new SimplePageTemplate<>(recyclerView, refreshLayout) {
            @Override
            public BaseQuickAdapter<Goods, BaseViewHolder> adapter(RecyclerView recyclerView) {
                recyclerView.setLayoutManager(new GridLayoutManager(getContext(), 3));
                recyclerView.addItemDecoration(new GoodsGridItemDecoration(AutoSizeUtils.dp2px(getContext(), 4)));

                BrowserHistoryAdapter favoritesAdapter = new BrowserHistoryAdapter();

                // 长按
                favoritesAdapter.setOnItemLongClickListener((adapter, view, position) -> {
                    View delete = view.findViewById(R.id.button_delete);
                    View mask = view.findViewById(R.id.view_background_mask);

                    if (delete.getVisibility() == View.VISIBLE) {
                        return true;
                    }

                    XHelper.setVisibility(View.VISIBLE, delete, mask);

                    Goods item = favoritesAdapter.getItem(position);
                    delete.setOnClickListener(v -> providerDeleteTemplate(favoritesAdapter).setParams(item.object_id).execute());

                    return true;
                });

                // 点击
                favoritesAdapter.setOnItemClickListener((adapter, view, position) -> {
                    View delete = view.findViewById(R.id.button_delete);
                    if (delete.getVisibility() == View.VISIBLE) {
                        View mask = view.findViewById(R.id.view_background_mask);
                        XHelper.setVisibility(View.INVISIBLE, delete, mask);
                        return;
                    }

                    Context context = view.getContext();
                    Goods goods = (Goods) adapter.getItem(position);
                    goods.id = goods.object_id;
                    context.startActivity(GoodsDetailsActivity.newIntent(context, goods));
                });

                return favoritesAdapter;
            }


            @Override
            public INetPageTask.Presenter<Goods, INetPageTask.View<Goods>> presenter() {
                return new NetPageTask<>() {
                    @Override
                    public Observable<? extends IResponse<? extends IPageResponse<Goods>>> execute(int page) {
                        return DataRepository.getInstance().favoritesGoodsList(page, PageResponse.SIZE);
                    }
                };
            }
        };
    }

    private SimpleParamsTemplate<Object, String> providerDeleteTemplate(BaseQuickAdapter<Goods, BaseViewHolder> adapter) {
        return new SimpleParamsTemplate<>() {
            @Override
            public INetTask.View<Object> view() {
                return new INetTask.View<>() {
                    @Override
                    public void success(Object data) {
                        List<Goods> goodsList = adapter.getData();
                        for (int index = 0; index < goodsList.size(); index++) {
                            if (goodsList.get(index).object_id.equals(params[0])) {
                                adapter.removeAt(index);
                                break;
                            }
                        }
                    }
                };
            }

            @Override
            public INetTask.Presenter<Object, INetTask.View<Object>> presenter() {
                return new NetSingleTask<>(DataRepository.getInstance().favoritesGoods(params[0], false));
            }
        };
    }

    @Override
    public boolean hasData() {
        return recyclerView != null
                && recyclerView.getAdapter() != null
                && recyclerView.getAdapter().getItemCount() > 1;
    }


    @Subscribe
    public void onEvent(FavoritesEvent event) {
        if (event != null && event.type == 0) {
            BrowserHistoryAdapter adapter = (BrowserHistoryAdapter) recyclerView.getAdapter();
            if (adapter != null) {
                int size = adapter.getData().size();
                adapter.setNewInstance(new ArrayList<>());
                adapter.notifyItemRangeRemoved(0, size);
            }
        }
    }

}
